<template>
  <el-dialog
    v-model="visible"
    title="菜单配置"
    width="800px"
    top="5vh"
    append-to-body
    :close-on-press-escape="false"
    :close-on-click-modal="false"
  >
    <el-row :gutter="10" class="mb-2">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd">新增</el-button>
      </el-col>
    </el-row>

    <el-table ref="tableRef" v-loading="loading" :data="list" height="260px">
      <el-table-column prop="sysMenu.parentName" label="上级菜单" />
      <el-table-column prop="sysMenu.menuName" label="菜单名称" />
      <el-table-column prop="sysMenu.orderNum" label="显示排序" />
      <el-table-column prop="sysMenu.path" label="路由地址" />
      <el-table-column label="操作" fixed="right">
        <template #default="{ row }">
          <el-button link icon="Edit" @click="handleUpdate(row)">修改</el-button>
          <el-button link icon="Delete" style="color: red" @click="handleDelete(row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      v-model:page="pageParams.pageNum"
      v-model:limit="pageParams.pageSize"
      :total="total"
      @pagination="getList"
    />

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="visible = false">取消</el-button>
      </div>
    </template>

    <el-dialog
      v-model="open"
      :title="title"
      width="680px"
      append-to-body
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-form ref="menuRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="子系统" prop="system">
          <el-select v-model="form.system" placeholder="请选择子系统">
            <el-option
              v-for="dict in gen_sys_list"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="上级菜单" prop="parentId">
          <el-tree-select
            v-model="form.parentId"
            :data="menuOptions"
            :props="{ value: 'menuId', label: 'label', children: 'children' }"
            value-key="menuId"
            placeholder="请选择上级菜单"
            check-strictly
            @change="handleParentIdChange"
          />
        </el-form-item>
        <el-form-item label="菜单名称" prop="menuName">
          <el-input v-model="form.menuName" placeholder="请输入菜单名称" />
        </el-form-item>
        <el-form-item label="显示排序" prop="orderNum">
          <el-input-number
            v-model="form.orderNum"
            placeholder="请输入显示排序"
            controls-position="right"
            :min="0"
            :step="1"
            step-strictly
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="路由地址" prop="path">
          <el-input v-model="form.path" placeholder="请输入路由地址" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确定</el-button>
          <el-button @click="cancel">取消</el-button>
        </div>
      </template>
    </el-dialog>
  </el-dialog>
</template>

<script setup>
  import { ref, watch, computed, defineProps, defineEmits } from 'vue';
  import { addPerm, updatePerm, removePerm, getPermList, getAllMenu } from '@/api/web/bu/form/perm';
  import { handleTree } from '@/utils/base';
  import { useDict } from '@/utils/dict';
  import modal from '@/plugins/modal';

  const props = defineProps({
    modelValue: {
      type: Boolean,
      default: false,
    },
    permId: {
      type: String,
      default: '',
    },
    tableCode: {
      type: String,
      default: '',
    },
  });
  const emits = defineEmits(['update:modelValue']);
  const { gen_sys_list } = useDict('gen_sys_list');

  const visible = computed({
    set(val) {
      emits('update:modelValue', val);
    },
    get() {
      return props.modelValue;
    },
  });

  const pageParams = ref({
    pageNum: 1,
    pageSize: 10,
  });
  const total = ref(0);
  const loading = ref(false);
  const list = ref([]);
  const open = ref(false);
  const title = ref('');
  const form = ref({});
  const menuRaw = ref([]);
  const menuOptions = ref([]);
  const menuRef = ref(null);

  const rules = ref({
    system: [{ required: true, message: '子系统不能为空', trigger: 'blur' }],
    parentId: [{ required: true, message: '上级菜单不能为空', trigger: 'blur' }],
    menuName: [{ required: true, message: '菜单名称不能为空', trigger: 'blur' }],
    orderNum: [{ required: true, message: '菜单顺序不能为空', trigger: 'blur' }],
    path: [{ required: true, message: '路由地址不能为空', trigger: 'blur' }],
  });

  watch(visible, (v) => {
    if (v) {
      handleQuery();
    }
  });

  function getList() {
    loading.value = true;
    getPermList(pageParams.value, { formTableId: props.permId })
      .then((res) => {
        list.value = res?.data?.records ?? [];
        total.value = res?.data?.total ?? 0;
      })
      .finally(() => {
        loading.value = false;
      });
  }

  function handleQuery() {
    pageParams.value.pageNum = 1;
    getList();
  }

  function getTreeselect() {
    menuOptions.value = [];
    getAllMenu().then((res) => {
      const menu = { menuId: 0, menuName: '根目录', label: '根目录', children: [] };
      menuRaw.value = res.data.map((k) => ({
        ...k,
        label: `#${k.orderNum} ${k.menuName}`,
      }));
      menu.children = handleTree(menuRaw.value, 'menuId');
      menuOptions.value.push(menu);
    });
  }

  function reset() {
    form.value = {
      menuId: null,
      menuName: null,
      parentId: 0,
      parentName: '根目录',
      orderNum: null,
      path: null,
      component: 'web/bu/curd/index',
      query: `{"id":"${props.permId}","tableCode":"${props.tableCode}"}`,
      isFrame: '1',
      isCache: '0',
      menuType: 'C',
      visible: '0',
      status: '0',
      perms: '',
      icon: null,
      system: null,
      remark: null,
    };
    menuRef.value?.resetFields();
  }

  function handleAdd() {
    reset();
    getTreeselect();
    title.value = '添加菜单';
    open.value = true;
  }

  function handleUpdate(row) {
    reset();
    getTreeselect();
    form.value = { ...row.sysMenu };
    title.value = '修改菜单';
    open.value = true;
  }

  function cancel() {
    open.value = false;
  }

  function submitForm() {
    menuRef.value?.validate((valid) => {
      if (valid) {
        if (form.value.menuId) {
          const params = {
            ...form.value,
            type: 1,
          };
          updatePerm(params).then(() => {
            modal.msgSuccess('修改成功');
            open.value = false;
            getList();
          });
        } else {
          const params = {
            sysMenu: form.value,
            formTableId: props.permId,
            type: 1,
          };
          addPerm(params).then(() => {
            modal.msgSuccess('新增成功');
            open.value = false;
            getList();
          });
        }
      }
    });
  }

  function handleDelete(row) {
    modal
      .confirm('是否确认删除名称为"' + row?.sysMenu?.menuName + '"的数据项?')
      .then(function () {
        return removePerm([row.id]);
      })
      .then(() => {
        getList();
        modal.msgSuccess('删除成功');
      })
      .catch(() => {});
  }

  function handleParentIdChange(v) {
    const one = menuRaw.value.find((k) => k.menuId === v);
    if (one) {
      form.value.parentName = one.menuName;
    }
  }
</script>
